# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(magrittr)
library(ropls)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read_tsv(opt$g) %>%
  rename(SampleID = Sample) %>%
  select(c("SampleID", "ClassNote"))

data <- read_tsv(opt$i) %>%
  rename(Metabolite = 1) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

classNotes <- unique(sampleInfo$ClassNote)
cn <- combn(classNotes, 2)
for (i in 1:ncol(cn)) {
  load("oplsda.RData")

  perMN <- plsdaRs@suppLs$permMN %>%
    as.data.frame() %>%
    set_colnames(c("R2X", "R2Y", "Q2", "RMSEE", "pre", "ort", "Similarity")) %>%
    select(-c("pre", "ort")) %>%
    arrange(Similarity)
  parent <- paste0("./")
  createWhenNoExist(parent)
  perFileName <- paste0(parent, "/OPLSDA_Permutation.csv")
  write.csv(perMN, perFileName)
}



